<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../themes/icon.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="../js/jquery.serializejson.min.js"></script>
</head>
<body>
        <div class="easyui-layout" data-options="fit:true">
                <div data-options="region:'west',split:true" title="West" style="width:150px;">
                        <ul id="tt"></ul>
                </div>
                <div data-options="region:'center',title:'Main Title',iconCls:'icon-ok'">
                        <table id="dg"></table>
                        <div id="dlg" class="easyui-dialog" title="数据操作" data-options="iconCls:'icon-save',closed:true" style="width:400px;max-height:400px;padding:10px">
                                <form id="ff" method="post">
                                    <input class="easyui-textbox" name="_id" style="width:100%" data-options="label:'_Id:'">
                                    <input id="pid" class="easyui-textbox" name="cateId" style="width:100%" data-options="label:'cateId:'">
                                    <div style="margin-bottom:20px">
                                        <input class="easyui-textbox" name="title" style="width:100%" data-options="label:'标题:',required:true">
                                    </div>
                                    <div style="margin-bottom:20px">
                                        <input class="easyui-textbox" name="content" style="width:100%" data-options="label:'内容:',required:true">
                                    </div>
                                    <div style="margin-bottom:20px">
                                        <input class="easyui-textbox" name="author" style="width:100%" data-options="label:'作者:',required:true">
                                    </div>
                                    <a href="#" id="dataSubmit" class="easyui-linkbutton" data-options="iconCls:'icon-add'">提交数据</a>
                                </form>
                        </div>


                        	<!-- 评论模块 -->
			<div id="comment" class="easyui-dialog" title="comment" data-options="iconCls:'icon-save',closed:true" style="width:800px;height:400px;padding:10px">
				<div data-options="region:'north" style="height:200px">
					
					<table id="dg"></table>
					
				</div>
				<!-- 数据内容 -->
				<div data-options="region:'south',title:'South Title',split:true" style="height:100px;width:80%">
					<form id="commentForm" method="post" style="height: 250px;">
						<div style="margin-top:20px" class='content-input'>
							
								<input class="easyui-textbox" name="_id" style="width:100%" data-options="label:'ID:'">

							<lable style="vertical-align: top;">评论标题:</lable>
							<input class="easyui-textbox" name="title" style="width:90%;height:40px">
						</div>
						<!-- <div style="margin-top:20px"> -->
							<lable style="vertical-align: top;">评论内容:</lable>
							<textarea name="desc" class="xheditor" rows="10" cols="10" style="width:90%;height:100px;"></textarea>
						<!-- </div> -->
					</form>
					<div data-options="region:'south'" style="height:200px">
						<a href="javascript:void(0)" class="easyui-linkbutton" onclick="postForm()" style="width:80px">评论</a>
						<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">清空</a>
					</div>
				</div>

			</div>
                </div>
        </div>
        <div id="ft" style="padding:2px 6px">
                <input class="easyui-searchbox" data-options="prompt:'Please Input Title',searcher:doSearch" style="width:200px">
        </div>
</body>
</html>
<script>
   $('#tt').tree({
        url:'http://localhost:3000/cate/list/1',
        method:'get',
        onClick:function(node){
            console.log(node);
            dgInit(node._id);
        }
        
   });
   function dgInit(cateId){
       var queryParams={};
       if(cateId){
            var queryParams=Object.assign(queryParams,{
                cateId:cateId
            })
       }
       $('#dg').datagrid({
        url: 'http://localhost:3000/news/list',
        fit: true,
        pagination: true,
        pageSize: 5,
        method: 'post',
        pageList: [5, 10, 20, 30, 40, 50],
        queryParams:queryParams,
        columns: [[
            { field: 'ck', checkbox: true },
            { field: 'title', title: '标题', width: 100 },
            { field: 'content', title: '内容', width: 100 },
            { field: 'author', title: '作者', width: 100 },
            { field: 'date' , title: '日期', width: 100 },
            {
                field: 'operate', title: '操作', width: 200,
                formatter: function (value, row, index) {
                    //console.log(index);
                    return "<a href='javascript:void(0)' onclick=onDelete('" + row._id + "')>删除</a> <a href='javascript:void(0)' onclick=onEdit('" + row._id + "')>修改</a> <a href='javascript:void(0)' onclick=onComment('" + row._id + "')>评论</a>"
                }
            }
        ]],
        toolbar: [{
            iconCls: 'icon-add',
            handler: function () {
                // 打开之前
                $('#ff').form('clear');
                $('#dlg').dialog('open');
                $("#pid").textbox('setValue',cateId);
                if(cateId==undefined){
                    $('#dlg').dialog('close');
                    $.messager.alert("提示!","未获取到cateId！请点击新闻分类！");
                }
                // console.log(cateId);
            }
        }, '-', {
            iconCls: 'icon-remove',
            handler: function () {
                var ids = [];
                //删除按钮在点击以后要做的事情是什么？
                var rows = $("#dg").datagrid('getSelections');
                if (rows.length > 0) {
                    for (var i = 0; i < rows.length; i++) {
                        ids.push(rows[i]._id)
                    }
                }
                if(rows!=''){
                     $.ajax({
                        url: 'http://localhost:3000/news/data/removes',
                        data: {
                            ids: ids.toString()
                        },
                        type: 'post'
                    }).then(res => {
                        $("#dg").datagrid('reload');
                    })
                }
            }
        }],
        header: '#ft'
    });
   }
  dgInit();
    $("#dataSubmit").click(function () {
        var formData = $('#ff').serializeJSON();
        if (formData._id.trim().length > 0) {
            // 修改
            $.ajax({
                url: `http://localhost:3000/news/data/${formData._id}`,
                data: formData,
                type: 'put'
            }).then(function (res) {
                $("#dlg").dialog('close');
                // 调用方式是在组件的外部进行调用
                $("#dg").datagrid("reload");
            })
        } else {
                delete formData._id;
                $.ajax({
                    url: 'http://localhost:3000/news/data',
                    data: formData,
                    type: 'post'
                }).then(function (res) {
                    $("#dlg").dialog('close');
                    // 调用方式是在组件的外部进行调用
                    $("#dg").datagrid("reload");
                })
        }
    })
    function onDelete(id) {
        //console.log(id);
        $.messager.confirm('删除确认操作', '你确认删除该记录?', function (r) {
            if (r) {
                $.ajax({
                    url: `http://localhost:3000/news/data/${id}`,
                    type: 'delete'
                }).then(res => {
                    if (res.status === 200) {
                        $.messager.show({
                            title: '信息的显示',
                            msg: res.message,
                            showType: 'show'
                        });
                        $('#dg').datagrid('reload');
                    }
                })
            }
        });
    }
    //--------------评论模块
var parentid = null;
var num = null ;
		//评论模块
		function onComment(id){
			parentid = id;
			console.log(id);
			$.ajax({
				type:"post",
				url:"http://localhost:3000/comm/list",
				async:true
			}).done(function(res){
				$('#comment').dialog('open');
				$('#comment #dg').datagrid({
					queryParams:{
						cateId:id
					}
				}).datagrid('reload')
			})
		}
		//评论表
		$('#comment #dg').datagrid({
		    url:'http://localhost:3000/comm/list',
			method:'post',
		    fit:true,
		    pagination:true,
		    pageSize:5,
		    pageList:[5,10,15],
		    columns:[[
		    	{field:'ck',title:'复选',checkbox:true},
		        {field:'title',title:'评论标题',width:100},
				{field:'desc',title:'评论内容',width:200},
		        {field:'operate',title:'操作', width:80,
					formatter: function(value,row,index){
						return "<a onclick=deletecom('"+ row._id+"')>删除</a> <a onclick=updatacom('"+ row._id+"')>修改</a>"
					}
				}
			]]
		});
		//添加评论按钮
		function postForm(){
			//评论数= 搜索total
			$.ajax({
				type:"post",
				url:"http://localhost:3000/comm/list",
				async:true,
				data:{
					cateId:parentid
				}
			}).done(function(data){
				num=data.total;
				console.log(num);
			});	
 
			var postData = $("#commentForm").serializeJSON();
			 
			postData.cateId = parentid;
			console.log(postData);
			if(postData._id.length>0){
					delete postData.cateId;
					
    				// edit
    				$.ajax({
	    				type:"put",
	    				url:"http://localhost:3000/comm/data/"  + postData._id,
	    				data: postData,
	    				async:true
	    			}).done(function(res){
	    				clearForm();
	    				$.messager.show({
							title:'信息提示',
							msg:'数据修改成功',
							timeout:3000,
							showType:'show'
		            	});
		           		$('#comment #dg').datagrid('reload');
	    			})
    			}else{	
    				// add
					delete postData._id;
					
					$.ajax({
						type:"post",
						url:"http://localhost:3000/comm/data",
						data: postData,
						async:true
					}).done(function(res){
						$.messager.show({
							title:'信息提示',
							msg:'数据添加成功',
							timeout:3000,
							showType:'show'
						});
						$('#comment #dg').datagrid('reload');
						clearForm();
						// 成功后评论数要更新
						$.ajax({
							type:"put",
							url:"http://localhost:3000/news/data/" + parentid,
							data: {num:++num},
							async:true
						}).done(function(res){
							$('#dg').datagrid('reload');
						});
					});
				}
		}				
		//删除评论
		function deletecom(id){
			console.log(id);
			$.messager.confirm('确认删除', '你确认删除数据吗？', function(r){
				if (r){
					$.ajax({
						type:"delete",
						url:"http://localhost:3000/comm/data/" + id,
						async:true
					}).done(function(res){
						// 成功后评论数要更新
						$('#comment #dg').datagrid('reload');
						num < 0 ? 0 : num ;
						$.ajax({
							type:"put",
							url:"http://localhost:3000/news/data/" + parentid,
							data: {num:--num},
							async:true
						}).done(function(res){
							$('#dg').datagrid('reload');
						});
					})
				}
			});
		}
		//修改评论
		function updatacom(id){
			$.ajax({
				type:"put",
				url:"http://localhost:3000/comm/data/" +id,
				async:true
			}).done(function(res){
				console.log(res);
				$('#comment #dg').datagrid('reload');
				$('#commentForm').form('load', res);
			})
		}
		

		//删除按钮
		function deleteData(id){
			$.messager.confirm('确认删除', '你确认删除数据吗？', function(r){
				if (r){
					$.ajax({
						type:"delete",
						url:"http://localhost:3000/news/data/" + id,
						async:true
					}).done(function(res){
						$("#dg").datagrid('reload');
					})
				}
			});
		}
		//删除多个按钮
		$("#removesBtn").click(function(){
			var rows = $("#dg").datagrid('getSelections');
			if(rows.length>0){
				var ids = [];
				rows.forEach(function(item,idx){
					ids.push(item._id)
				})
				console.log(ids);
				$.messager.confirm('确认删除', '你确认删除数据吗？', function(r){
					if (r){
						for(var i=0;i<ids.length;i++){
							$.ajax({
								type:"delete",
								url:"http://localhost:3000/news/data/" + ids[i],
								data:{
									ids: ids.toString()
								},
								async:true
							}).done(function(res){
								$("#dg").datagrid('reload');
							});
						}
					}
				});	
			}
		})
		function clearForm(){
			$('#ff').form('clear');
			$('#commentForm').form('clear');
			$('textarea').val(' ');
		}
		//所有新闻
    		$("#loadAllDataBtn").click(function(){
    			cateId = null;
    			 $("#dg").datagrid({
					queryParams: {
						cateId: cateId
					}
				}).datagrid('reload');
    		})
    		//查询
    		function doSearch(value){
            $("#dg").datagrid({
				queryParams: {
					cateId: cateId,
					title: value
				}
			}).datagrid('reload');
		}
    function onEdit(id) {
        //console.log(id);
        $.ajax({
            url: `http://localhost:3000/news/data/${id}`,
            type: 'get'
        }).then(res => {
            $('#ff').form('load', res);
            $("#dlg").dialog('open');
        })
    }
    function doSearch(value) {
		$("#dg").datagrid({
			queryParams: {
				title: value
			}
		}).datagrid('reload');
	}
</script>